package com.yoo.ons.function.register

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.text.TextUtils
import android.util.Log
import android.view.inputmethod.InputMethodManager
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import android.window.OnBackInvokedDispatcher
import androidx.core.content.ContextCompat
import androidx.core.view.allViews
import androidx.core.view.get
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.bumptech.glide.Glide
import com.github.gzuliyujiang.wheelpicker.annotation.DateMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import com.yoo.chat.kit.widget.refresh.util.DesignUtil
import com.yoo.module_base.utils.GlideUtil
import com.yoo.module_base.utils.PictureSelectTypeUtil
import com.yoo.module_base.utils.SaveDeviceUtil
import com.yoo.module_base.utils.ScreenUtils
import com.yoo.module_base.utils.StatusBarUtil
import com.yoo.module_base.utils.date.DateUtil
import com.yoo.module_base.view.EnglishDateFormatter
import com.yoo.ons.R
import com.yoo.ons.ToastUtil
import com.yoo.ons.adapter.ChooseGenderAdapter
import com.yoo.ons.base.BaseVMActivity
import com.yoo.ons.base.HttpRequestListener
import com.yoo.ons.databinding.ActivityRegisterBinding
import com.yoo.ons.dialog.LoadingDialog
import com.yoo.ons.dialog.PictureSelectTypePopup
import com.yoo.ons.function.MainActivity
import com.yoo.ons.function.register.viewmodel.RegisterViewModel
import com.yoo.ons.listener.PictureManagerListener
import com.yoo.ons.model.DispositionModel
import com.yoo.ons.model.PictureManagerModel
import com.yoo.ons.model.RegisterDispositionModel
import com.yoo.ons.model.RegisterListModel
import com.yoo.ons.model.UserInfoModel
import com.yoo.ons.util.UploadPhotoUtil
import com.yoo.ons.view.PictureManagerView
import java.util.Calendar
import kotlin.reflect.jvm.internal.impl.util.Check

class RegisterActivity : BaseVMActivity<ActivityRegisterBinding, RegisterViewModel>(
    ActivityRegisterBinding::inflate,
    RegisterViewModel::class.java
) {
    private var step = 1//表示注册步骤
    private var chooseGender = 1 // 1男2女0未知
    private var selectDateValue = ""//默认的生日
    private var iWantCode: Long = -1//获取选择的now i want的code
    private val acceptCodeList = arrayListOf<Long>()//获取you accept的code列表
    private var iwantList: ArrayList<RegisterListModel> = arrayListOf(
        RegisterListModel(248, "\uD83D\uDC60  Short-term fling", "", 0),
        RegisterListModel(249, "\uD83D\uDC91  Long-term commitment", "", 0)
    )//配置默认的now i want参数，当无数据返回时使用
    private var youAcceptList: ArrayList<RegisterListModel>? = null
    private var model: RegisterDispositionModel? = null
    private var photoList = arrayListOf(
        PictureManagerModel("", "", "",false),
        PictureManagerModel("", "", "",false),
        PictureManagerModel("", "", "",false),
        PictureManagerModel("", "", "",false),
        PictureManagerModel("", "", "",false),
        PictureManagerModel("", "", "",false)
    )//设置默认的照片集合
    private val bodyShape:ArrayList<Long> = arrayListOf() //获取选择的性别爱好code
    override fun initData() {
        mViewModel?.getRegisterDisposition(object :
            HttpRequestListener<RegisterDispositionModel>() {
            override fun addRequestParams(params: HashMap<String, Any>) {

            }

            override fun success(t: RegisterDispositionModel?) {
                model = t
            }

            override fun endRequest() {
                super.endRequest()
                setSelectBirthDate()
            }

        })
    }

    override fun initView() {
        super.initView()
        //返回按钮的事件判断
        binding.titleBar.setBackListener {
            setBackPageShow()
        }
        binding.titleBar.setTitleBarPadding(StatusBarUtil.getStatusBarHeight(this))
    }

    @SuppressLint("MissingSuperCall")
    override fun onBackPressed() {
        setBackPageShow()
    }


    /**
     * 下一步显示页面判断
     */
    private fun setNextPageShow() {
        when (step) {
            2 -> {
                binding.registerScheduleProgress.progress = 40
                binding.selectBirthDateContainer.isVisible = false
                binding.editNameContainer.isVisible = true
            }

            3 -> {
                binding.registerScheduleProgress.progress = 60
                binding.editNameContainer.isVisible = false
                binding.chooseGenderContainer.isVisible = true
            }

            4 -> {
                binding.registerScheduleProgress.progress = 80
                binding.chooseGenderContainer.isVisible = false
                binding.uploadPhotoContainer.isVisible = true
            }

            5 -> {
                binding.registerScheduleProgress.progress = 100
                binding.uploadPhotoContainer.isVisible = false
                binding.wantAcceptContainer.isVisible = true
            }
        }
    }

    /**
     * 返回上一步显示页面判断
     * when(step)判断的step为当前步骤，返回之后修改step值
     */
    private fun setBackPageShow() {
        when (step) {
            1 -> {
                finish()
            }

            2 -> {
                step = 1
                binding.registerScheduleProgress.progress = 20
                binding.selectBirthDateContainer.isVisible = true
                binding.editNameContainer.isVisible = false
            }

            3 -> {
                step = 2
                binding.registerScheduleProgress.progress = 40
                binding.editNameContainer.isVisible = true
                binding.chooseGenderContainer.isVisible = false
            }

            4 -> {
                step = 3
                binding.registerScheduleProgress.progress = 60
                binding.chooseGenderContainer.isVisible = true
                binding.uploadPhotoContainer.isVisible = false
            }

            5 -> {
                step = 4
                binding.registerScheduleProgress.progress = 80
                binding.uploadPhotoContainer.isVisible = true
                binding.wantAcceptContainer.isVisible = false
            }
        }
    }

    /**
     * 年龄选择页面配置
     */
    private fun setSelectBirthDate() {
        binding.registerScheduleProgress.isVisible = true
        binding.selectBirthDateContainer.isVisible = true

        model?.apply {
            //获取性别参数
            val birthDateModelList = this.configs.filter {
                it.pageType == 1
            }
            if (!birthDateModelList.isNullOrEmpty()) {
                val birthDateModel = birthDateModelList[0]
                binding.txtSelectBirthDateTitle.text = birthDateModel.firstTitle
                binding.txtSelectBirthDateTips.text = birthDateModel.additional
                binding.txtSelectBirthDateAgeTips.text = birthDateModel.firstContent
            }
        }

        binding.txtSelectBirthDateNext.setOnClickListener {
            step = 2
            setNextPageShow()
            setNickName()
        }


        //日期控件参数设置
        binding.dateSelectLayout.setDateMode(DateMode.YEAR_MONTH_DAY)
        val c = Calendar.getInstance()
        //设置最小可选年份
        c.add(Calendar.YEAR, -18)
        selectDateValue =
            "${DateEntity.target(c).month}-${EnglishDateFormatter().formatDay(DateEntity.target(c).day)}-${
                DateEntity.target(c).year
            }"
        //设置当前选择的年月日
        binding.dateSelectLayout.setRange(
            DateEntity.target(c.weekYear - 42, 1, 1),
            DateEntity.target(c),
            DateEntity.target(c)
        )
        binding.dateSelectLayout.setVisibleItemCount(5)
        binding.dateSelectLayout.setItemSpace(ScreenUtils.dip2px(this, 45f))
        binding.dateSelectLayout.setAtmosphericEnabled(false)
        binding.dateSelectLayout.setIndicatorEnabled(true)
        binding.dateSelectLayout.setIndicatorColor(
            ContextCompat.getColor(
                this,
                com.yoo.module_res.R.color.color_D34EFF
            )
        )
        binding.dateSelectLayout.setIndicatorSize(ScreenUtils.dp2pxF(this, 1f))
        binding.dateSelectLayout.setTextColor(Color.WHITE)
        binding.dateSelectLayout.setSelectedTextColor(
            ContextCompat.getColor(
                this,
                com.yoo.module_res.R.color.color_FF3EAB
            )
        )
        //设置字体
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            binding.dateSelectLayout.dayWheelView.typeface =
                resources.getFont(com.yoo.module_res.R.font.lexenddeca_medium)
            binding.dateSelectLayout.monthWheelView.typeface =
                resources.getFont(com.yoo.module_res.R.font.lexenddeca_medium)
            binding.dateSelectLayout.yearWheelView.typeface =
                resources.getFont(com.yoo.module_res.R.font.lexenddeca_medium)
        }
        //日期选择监听
        binding.dateSelectLayout.setOnDateSelectedListener { year, month, day ->
            selectDateValue =
                "${DateUtil.getMonths()[month - 1]}-${EnglishDateFormatter().formatDay(day)}-$year"
        }
    }

    /**
     * 昵称填写页面配置
     */
    private fun setNickName() {
        model?.apply {
            //获取性别参数
            val nickNameModelList = this.configs.filter {
                it.pageType == 2
            }
            //当昵称不为空时设置页面
            if (!nickNameModelList.isNullOrEmpty()) {
                val nickNameModel = nickNameModelList[0]
                //设置一级标题和内容
                binding.txtEditNameTitle.text = nickNameModel.firstTitle
                binding.txtEditNameTip.text = nickNameModel.firstContent

                //设置默认昵称
                binding.editName.setText(nickNameModel.nickName ?: "")
                binding.editName.setSelection(nickNameModel.nickName?.length ?: 0)
                binding.txtEditNameNext.isEnabled = !binding.editName.text.isNullOrEmpty()
            }
        }
        //展示软键盘
        binding.editName.postDelayed({
            binding.editName.requestFocus()
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.showSoftInput(binding.editName, InputMethodManager.SHOW_IMPLICIT)
        }, 100)
        //输入框监听
        binding.editName.addTextChangedListener {
            binding.txtEditNameNext.isEnabled = !binding.editName.text.isNullOrEmpty()
        }

        binding.txtEditNameNext.setOnClickListener {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(binding.editName.windowToken, 0)

            step = 3
            setNextPageShow()
            setGender()
        }
    }

    /**
     * 性别选择页面配置
     */
    private fun setGender() {
        var chooseGenderAdapter: ChooseGenderAdapter? = null
        var genderModel: DispositionModel? = null
        model?.apply {
            //获取性别参数
            val genderModelList = this.configs.filter {
                it.pageType == 3
            }
            //当性别不为空时设置页面
            if (!genderModelList.isNullOrEmpty()) {
                genderModel = genderModelList[0]
                genderModel?.apply {
                    binding.txtChooseGenderTitle.text = this.firstTitle
                    if (this.secondTitle == null) {
                        //当二级标题为null时，不展示性别爱好选择，Next默认可点击
                        binding.txtChooseGenderNext.isEnabled = true
                        binding.txtChooseGenderSecondTitle.isVisible = false
                        binding.txtChooseGenderSecondTip.isVisible = false
                        binding.genderInterestList.isVisible = false
                        return
                    }
                    binding.txtChooseGenderSecondTitle.text = this.secondTitle
                    binding.txtChooseGenderSecondTip.text = this.secondContent
                    //默认选择男性
                    (binding.genderInterestList.itemAnimator as SimpleItemAnimator).supportsChangeAnimations =
                        false
                    binding.genderInterestList.layoutManager = GridLayoutManager(this@RegisterActivity, 3)
                    chooseGenderAdapter = ChooseGenderAdapter(this@RegisterActivity) {
                        if (binding.rbFemale.isChecked) {
                            binding.txtChooseGenderNext.isEnabled = !this.bodyShapeForWoman.filter { it.selected == 1 }.isNullOrEmpty()
                        } else if (binding.rbMale.isChecked) {
                            binding.txtChooseGenderNext.isEnabled = !this.bodyShapeForMan.filter { it.selected == 1 }.isNullOrEmpty()
                        }
                    }
                    chooseGenderAdapter?.addAll(this.bodyShapeForMan)
                    binding.genderInterestList.adapter = chooseGenderAdapter
                }

            } else {
                //当无法获取到性别配置信息时，默认选择男性，next可点击
                binding.txtChooseGenderNext.isEnabled = true
            }
        }
        if (model == null) {
            //当无法获取到注册配置信息时，默认选择男性，next可点击
            binding.txtChooseGenderNext.isEnabled = true
            binding.txtChooseGenderSecondTitle.isVisible = false
            binding.txtChooseGenderSecondTip.isVisible = false
            binding.genderInterestList.isVisible = false
        }

        //性别选择
        binding.rgSexChoose.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_female -> {
                    if (chooseGender != 2) {//当已选择的性别不为女时，清除iwant和you accept的选项
                        iWantCode = -1
                        acceptCodeList.clear()
                    }

                    if (model != null) {
                        binding.txtChooseGenderNext.isEnabled =
                            !genderModel?.bodyShapeForWoman?.filter { it.selected == 1 }
                                .isNullOrEmpty()
                        //显示爱好选择
                        binding.txtChooseGenderSecondTitle.isVisible = true
                        binding.txtChooseGenderSecondTip.isVisible = true
                        binding.genderInterestList.isVisible = true
                        chooseGenderAdapter?.let {
                            //更新爱好选择列表
                            it.getDataList().clear()
                            genderModel?.apply {
                                it.addAll(this.bodyShapeForWoman)

                            }
                            it.notifyDataSetChanged()
                        }
                    }

                    //更新选择值
                    chooseGender = 2
                }

                R.id.rb_male -> {
                    if (chooseGender != 1) {//当已选择的性别不为男时，清除iwant和you accept的选项
                        iWantCode = -1
                        acceptCodeList.clear()
                    }

                    if (model != null) {
                        binding.txtChooseGenderNext.isEnabled =
                            !genderModel?.bodyShapeForMan?.filter { it.selected == 1 }
                                .isNullOrEmpty()
                        //显示爱好选择
                        binding.txtChooseGenderSecondTitle.isVisible = true
                        binding.txtChooseGenderSecondTip.isVisible = true
                        binding.genderInterestList.isVisible = true
                        chooseGenderAdapter?.let {
                            //更新爱好选择列表
                            it.getDataList().clear()
                            genderModel?.apply {
                                it.addAll(this.bodyShapeForMan)
                            }
                            it.notifyDataSetChanged()
                        }
                    }


                    //更新选择值
                    chooseGender = 1
                }

                R.id.rb_queer -> {
                    if (chooseGender != 0) {//当已选择的性别不为酷儿时，清除iwant和you accept的选项
                        iWantCode = -1
                        acceptCodeList.clear()
                    }

                    binding.txtChooseGenderNext.isEnabled = true
                    //queer不需要选择爱好，隐藏爱好选择
                    binding.txtChooseGenderSecondTitle.isVisible = false
                    binding.txtChooseGenderSecondTip.isVisible = false
                    binding.genderInterestList.isVisible = false
                    //更新选择值
                    chooseGender = 0
                }
            }
        }

        binding.txtChooseGenderNext.setOnClickListener {
            if (chooseGender != 0) {//当选择的性别不为酷儿时，获取已选择的爱好code
                chooseGenderAdapter?.apply {
                    val filter = this.getDataList().filter { model ->
                        model.selected == 1
                    }
                    repeat(filter.size) { position ->
                        bodyShape.add(filter[position].code)
                    }
                }
            }
            step = 4
            setNextPageShow()
            setUploadPhoto()
        }

    }

    /**
     * 上传头像页面配置
     */
    private fun setUploadPhoto() {
        model?.apply {
            //获取性别参数
            val uploadPhotoModelList = this.configs.filter {
                it.pageType == 4
            }
            //当性别不为空时设置页面
            if (!uploadPhotoModelList.isNullOrEmpty()) {
                val uploadPhotoModel = uploadPhotoModelList[0]
                binding.txtUploadPhotoTitle.text = uploadPhotoModel.firstTitle
                binding.txtUploadPhotoTip.text = uploadPhotoModel.firstContent
            }
        }

        binding.pictureManagerView.setData(photoList)
        binding.pictureManagerView.addImageClickListener(object :PictureManagerListener{
            override fun imageClick(isAdd: Boolean) {
                if (isAdd) {
                    //上传照片
                    PictureSelectTypePopup(this@RegisterActivity,
                        object : PictureSelectTypePopup.SelectListener {
                            override fun onSelectAlbumsListener() {
                                PictureSelectTypeUtil.openAlbum(this@RegisterActivity)
                            }

                            override fun onSelectCameraListener() {
                                PictureSelectTypeUtil.openCamera(this@RegisterActivity)

                            }

                        }).showPopupWindow()
                }else{
                    //删除照片
                    val userImages = binding.pictureManagerView.userImages
                    userImages.removeAt(binding.pictureManagerView.photoSelectPosition)
                    binding.pictureManagerView.setData(userImages)
                }
            }

        })
        binding.txtUploadPhotoSkip.setOnClickListener {
            step = 5
            setNextPageShow()
            setNowIWant()
        }

        binding.txtUploadPhotoNext.setOnClickListener {
            step = 5
            setNextPageShow()
            setNowIWant()
        }
    }

    /**
     * now i want页面配置
     */
    private fun setNowIWant() {
        model?.apply {
            //获取now i want参数
            val nowIWantModelList = this.configs.filter {
                it.pageType == 5
            }
            //当now i want不为空时设置页面
            if (!nowIWantModelList.isNullOrEmpty()) {
                val nowIWantModel = nowIWantModelList[0]

                //设置一级标题内容
                binding.txtNowIWantTitle.text = nowIWantModel.firstTitle
                binding.txtNowIWantTip.text = nowIWantModel.firstContent

                //设置now i want
                if (!nowIWantModel.iwantList.isNullOrEmpty()) {
                    setNowIWantView(nowIWantModel.iwantList)
                }

                //如果二级标题为null，不展示you accept
                if (nowIWantModel.secondTitle == null) {
                    binding.txtYouAcceptTitle.isVisible = false
                    return
                }
                //设置二级标题
                binding.txtYouAcceptTitle.text = nowIWantModel.secondTitle

                //获取you accept列表，性别为男和queer都选择youAcceptForMan，性别为女选择youAcceptForWomen
                val youAcceptList =
                    if (binding.rbFemale.isChecked) nowIWantModel.youAcceptForWomen else nowIWantModel.youAcceptForMan
                this@RegisterActivity.youAcceptList = youAcceptList //获取配置youAcceptList参数
                if (!youAcceptList.isNullOrEmpty()) {
                    //先清除所有子view
                    binding.youAcceptList.removeAllViews()
                    for (i in 0 until youAcceptList.size) {
                        //动态创建CheckBox，并设置属性
                        val iWantModel = youAcceptList[i]
                        val checkBox = CheckBox(this@RegisterActivity)
                        checkBox.layoutParams = LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT,
                            DesignUtil.dp2px(this@RegisterActivity, 53f)
                        )
                        checkBox.text = iWantModel.value
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            checkBox.typeface =
                                resources.getFont(com.yoo.module_res.R.font.lexenddeca_regular)
                        }
                        checkBox.setTextColor(
                            ContextCompat.getColor(
                                this@RegisterActivity,
                                com.yoo.module_res.R.color.selector_gender_color
                            )
                        )
                        checkBox.setBackgroundResource(com.yoo.module_res.R.drawable.select_choose_gender)
                        checkBox.setPadding(
                            DesignUtil.dp2px(this@RegisterActivity, 23f),
                            0,
                            DesignUtil.dp2px(this@RegisterActivity, 23f),
                            0
                        )
                        checkBox.buttonDrawable = null
                        checkBox.textSize = 16f
                        // 设置外边距
                        val marginT = DesignUtil.dp2px(this@RegisterActivity, 8f)
                        val layoutParams = checkBox.layoutParams as LinearLayout.LayoutParams
                        layoutParams.setMargins(0, marginT, 0, 0)
                        checkBox.layoutParams = layoutParams
                        binding.youAcceptList.addView(checkBox)
                    }

                }
            }
        }

        if (model == null) {
            binding.txtYouAcceptTitle.isVisible = false
            binding.youAcceptList.isVisible = false
            setNowIWantView(iwantList)
        }


        binding.txtNowIWantNext.setOnClickListener {
            //获取选择的you accept的code
            youAcceptList?.apply {
                acceptCodeList.clear()
                for (i in 0 until binding.youAcceptList.childCount) {
                    if ((binding.youAcceptList[i] as CheckBox).isChecked) {
                        acceptCodeList.add(this[i].code)
                    }
                }
            }

            mViewModel?.getRegister(object :HttpRequestListener<UserInfoModel>(){
                override fun addRequestParams(params: HashMap<String, Any>) {
                    params["birthday"]=selectDateValue
                    params["nickName"]=binding.editName.text.toString()
                    params["gender"]=chooseGender
                    val pictureManagerModels = binding.pictureManagerView.userImages.filter { managerModel ->
                        managerModel.imageUrl != ""
                    }
                    params["avatarUrl"]=""
                    val list = arrayListOf<String>()
                    if (!pictureManagerModels.isNullOrEmpty()){
                        repeat(pictureManagerModels.size) { it1 ->
                            if (pictureManagerModels[it1].imageLoadUrl != "") {
                                list.add(pictureManagerModels[it1].imageLoadUrl)
                            }
                        }
                        params["avatarUrl"]= pictureManagerModels[0].imageUrl
                    }
                    params["images"]= list
                    params["lookingFor"]= if (chooseGender == 1) 2 else if (chooseGender == 2) 1 else 0
                    if (chooseGender != 0){
                        params["bodyShape"]=bodyShape
                    }
                    params["userWant"] = iWantCode
                    params["youAccept"] = acceptCodeList
                }

                override fun success(t: UserInfoModel?) {
                    SaveDeviceUtil.saveAvatarUrl(t?.avatarUrl)
                    Glide.with(this@RegisterActivity).load(t?.avatarUrl).preload()
                    SaveDeviceUtil.saveUserValid(true)
                    MainActivity.start(this@RegisterActivity)
                }

            })

        }

    }


    /**
     * 设置now i want列表view
     */
    private fun setNowIWantView(iwantList: List<RegisterListModel>) {
        //先清除所有子view
        binding.rgNowIWant.removeAllViews()
        for (iWantModel in iwantList) {
            //动态创建RadioButton，并设置属性
            val radioButton = RadioButton(this@RegisterActivity)
            radioButton.layoutParams = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                DesignUtil.dp2px(this@RegisterActivity, 53f)
            )
            radioButton.text = iWantModel.value
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                radioButton.typeface =
                    resources.getFont(com.yoo.module_res.R.font.lexenddeca_regular)
            }
            radioButton.setTextColor(
                ContextCompat.getColor(
                    this@RegisterActivity,
                    com.yoo.module_res.R.color.selector_gender_color
                )
            )
            radioButton.setBackgroundResource(com.yoo.module_res.R.drawable.select_choose_gender)
            radioButton.setPadding(
                DesignUtil.dp2px(this@RegisterActivity, 23f),
                0,
                DesignUtil.dp2px(this@RegisterActivity, 23f),
                0
            )
            radioButton.buttonDrawable = null
            radioButton.textSize = 16f
            // 设置外边距
            val marginT = DesignUtil.dp2px(this@RegisterActivity, 8f)
            val layoutParams = radioButton.layoutParams as LinearLayout.LayoutParams
            layoutParams.setMargins(0, marginT, 0, 0)
            radioButton.layoutParams = layoutParams
            binding.rgNowIWant.addView(radioButton)
        }
        binding.rgNowIWant.setOnCheckedChangeListener(object :
            RadioGroup.OnCheckedChangeListener {
            override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
                val checkedIndex = group?.indexOfChild(findViewById(checkedId))
                checkedIndex?.apply {
                    iWantCode = iwantList[checkedIndex].code
                }
                binding.txtNowIWantNext.isEnabled = true
            }
        })
        for (i in iwantList.indices) {
            if (iWantCode == iwantList[i].code) {
                (binding.rgNowIWant.getChildAt(i) as RadioButton).isChecked = true
            }
        }
    }



    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList = PictureSelector.obtainSelectorList(data)
                    addImage(selectList)
                }
            }
        }
    }

    private fun addImage(selectList: ArrayList<LocalMedia>?) {
        selectList?.forEach {
            val path = when {
                it.isCompressed -> {
                    it.compressPath
                }

                it.isCut -> {
                    it.cutPath
                }

                else -> {
                    it.realPath
                }
            }
            if (path.contains(".mp4", true) || it.mimeType.contains(
                    ".3gp",
                    true
                ) || it.mimeType.contains(".mov", true)
            ) {
                ToastUtil.showToast("pls upload photo.")
                return
            }
            val userPhotoBeans = binding.pictureManagerView.userImages
            val userPhotoBean = userPhotoBeans[binding.pictureManagerView.photoSelectPosition]
            val opType = if (TextUtils.isEmpty(userPhotoBean.imageUrl)) 1 else 2
            val imageCode = if (opType == 1) "" else {
                userPhotoBean.imageCode
            }
            showProgressDialog(this)
            UploadPhotoUtil.uploadPhoto(
                this,
                path,
                imageCode,
                object : UploadPhotoUtil.OnListener {
                    override fun onSuccess(successPath: String, imageCode: String) {
                        hideProgressDialog()
                        val opType = if (TextUtils.isEmpty(imageCode)) 1 else 2
                        savePhoto(
                            if (opType == 2)imageCode else "",
                            successPath,
                            path,
                            opType,binding.pictureManagerView
                        )

                    }

                    override fun fail() {
                        hideProgressDialog()
                        ToastUtil.showToast("upload error,pls try again")
                    }

                })
        }
    }


    /**
     * 保存照片
     */
    fun savePhoto(
        imageCode: String,
        imageUrl: String,
        path: String,
        opType: Int,
        pictureManagerView:PictureManagerView
    ) {
        val uploadPhotoList = pictureManagerView.userImages
        if (opType == 1) {
            var lastPosition = 0
            for (i in 0 until uploadPhotoList.size) {
                if (uploadPhotoList[i].imageUrl == "") {
                    lastPosition = i
                    break
                }
            }
            uploadPhotoList[lastPosition].imageUrl = imageUrl
            uploadPhotoList[lastPosition].imageLoadUrl = path
            uploadPhotoList[lastPosition].imageCode = imageCode
            uploadPhotoList[lastPosition].loading = false
            pictureManagerView.userImages = uploadPhotoList
            pictureManagerView.updateItemImage(lastPosition)
        } else if (opType == 2) {
            var lastPosition = 0
            for (i in 0 until uploadPhotoList.size) {
                if (uploadPhotoList[i].imageCode == imageCode) {
                    lastPosition = i
                    break
                }
            }
            uploadPhotoList[lastPosition].imageUrl = imageUrl
            uploadPhotoList[lastPosition].imageLoadUrl = path
            uploadPhotoList[lastPosition].imageCode = imageCode
            uploadPhotoList[lastPosition].loading = false
            pictureManagerView.userImages = uploadPhotoList
            pictureManagerView.updateItemImage(lastPosition)
        } else if (opType == 3) {
            val position = pictureManagerView.photoSelectPosition
            uploadPhotoList.removeAt(position)
            pictureManagerView.setData(uploadPhotoList)
        }

        binding.txtUploadPhotoNext.isEnabled=true
    }



    companion object {
        fun start(context: Context) {
            val intent = Intent(context, RegisterActivity::class.java)
            context.startActivity(intent)
        }
    }
}